<?php
/**
 * Created by PhpStorm.
 * User: Tangyijun
 * Date: 2017/4/20
 * Time: 16:37
 */
namespace app\admin\controller;
use app\data\Data;
use app\validate\AdminValidate;
use think\Config;
use think\Cookie;
use think\Request;

/**
 * +----------------------------------------------
 * Class Login
 * @package app\admin\controller
 * 管理员登录类
 * +----------------------------------------------
 */
class Login extends Base{
    /**
     * @return array|\think\response\View
     * 管理员登录
     */
    public function login(){
        try{
            if(Request::instance()->isPost()){
                $post = Request::instance()->post();
                $admin_validate = new AdminValidate();
                $validate_rule = $admin_validate->adminValidate();                                  /*获取验证规则*/
                self::validateData($validate_rule['rule'], $validate_rule['message'],$post);       /*验证数据*/
                $admin_info = $this->checkLogin($post);                                            /*验证登录信息*/
                Cookie::set('admin_id',$admin_info['id'],['prefix'=>'blog_','expire'=>3600*24*7]); /*存储用户信息*/
                return self::formatSuccessResult();
            }
        }catch(\Exception $e){
            return self::formatResult($e->getCode(),$e->getMessage());
        }
        return view('login');
    }

    /**
     * @param  array $data
     * @return array|false|mixed|\PDOStatement|string|\think\Model
     * 验证用户
     */
    protected function checkLogin($data = []){
        $admin = new Data('admin');
        $admin_info = $admin->find(['username'=>$data['username']],"id,username,password,status");
        //账户是否存在
        if(empty($admin_info)){
            throw new \LogicException(Config::get('error_table.acc_empty')['msg'],Config::get('error_table.acc_empty')['code']);
        }
        //账户是否被锁定
        if($admin_info['status'] == $admin::STATUS_OFF){
            throw new \LogicException(Config::get('error_table.acc_block')['msg'],Config::get('error_table.acc_block')['code']);
        }
        //密码是否正确
        $check_password = password_verify($data['password'],$admin_info['password']);
        if(!$check_password){
            throw new \LogicException(Config::get('error_table.password')['msg'],Config::get('error_table.password')['code']);
        }
        return $admin_info;
    }
    //退出
    public function logout(){
        cookie('admin_id',null);
        $this->redirect('Login/login');
    }
}